<template>
  <div class="app-container">

    <!-- 搜索部分页面 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选择分类" prop="categoryName">
  <el-select 
    v-model="queryParams.categoryName" 
    placeholder="请选择二级分类" 
    clearable
    filterable
    style="width: 100%"
  >
    <el-option
      v-for="dict in productcategories"
      :key="dict.value"
      :label="dict.label"
      :value="dict.value"
    >
      <span style="float: left">{{ dict.label }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.value }}</span>
    </el-option>
  </el-select>
</el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售状态" prop="isAvailable">
  <el-select 
    v-model="queryParams.isAvailable" 
    placeholder="请选择可购买？" 
    clearable
    style="width: 100%"
  >
    <el-option
      v-for="dict in sold_status"
      :key="dict.value"
      :label="dict.label"
      :value="dict.value"
    />
  </el-select>
</el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


  <!-- crud部分按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
  <el-button
    type="primary"
    plain
    icon="Plus"
    @click="handleAdd"
    v-hasPermi="['product:product:add']"
    v-show="showAddButton" 
  >添加商品</el-button>
</el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['product:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <!-- 列表展示页面 -->
    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名" align="center" prop="productName" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="商品库存" align="center" prop="stockQuantity" />
      <el-table-column label="分类" align="center" prop="categoryName">
        <template #default="scope">
          <dict-tag :options="productcategories" :value="scope.row.categoryName"/>
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="图片链接" align="center" prop="imageUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="可购买？" align="center" prop="isAvailable">
        <template #default="scope">
          <dict-tag :options="sold_status" :value="scope.row.isAvailable"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['product:product:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['product:product:remove']">删除</el-button>
        </template>
      </el-table-column>



      <el-table-column label="查看评论" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="getReviews(scope.row)" v-hasPermi="['cart:cart:list']">查看评论</el-button>
        </template>
      </el-table-column>


      <el-table-column label="购买数量" align="center" prop="quantity" class-name="small-padding fixed-width">
  <template #default="scope">
    <div style="display: flex; align-items: center;">
      <el-button link type="primary" icon="Plus" @click="increaseQuantity(scope.row)">1</el-button>
      <span style="margin-left: 8px;">{{ scope.row.quantity }}</span>
    </div>
  </template>
  
</el-table-column>

<el-table-column label="总价" align="center" prop="total_amount" />

      <el-table-column label="购买" align="center" class-name="small-padding fixed-width">
  <template #default="scope">
    <el-button link type="success" icon="ShoppingCart" @click="addToCart(scope.row)" v-show="showBuyButton"  >购买</el-button>
  </template>
</el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 查看评论对话框 -->
<el-dialog title="商品评论" v-model="reviews" width="700px" append-to-body>
  <el-table :data="reviewsList" v-loading="loading" style="width: 100%">
    <el-table-column prop="userName" label="用户" width="120" align="center"/>
    <el-table-column label="评分" width="120" align="center">
      <template #default="scope">
        <el-rate v-model="scope.row.rating" disabled show-score text-color="#ff9900" />
      </template>
    </el-table-column>
    <el-table-column prop="comment" label="评论内容" align="center"/>
    <el-table-column prop="reviewDate" label="评论时间" width="180" align="center"/>
  </el-table>
  
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="reviews = false">关闭</el-button>
    </div>
  </template>
</el-dialog>

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="商品库存" prop="stockQuantity">
          <el-input v-model="form.stockQuantity" placeholder="请输入商品库存" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="图片链接" prop="imageUrl">
          <image-upload v-model="form.imageUrl"/>
        </el-form-item>
        <el-form-item label="销售状态" prop="isAvailable">
          <el-select v-model="form.isAvailable" placeholder="请选择可购买？">
            <el-option
              v-for="dict in sold_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">分类信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddCategorie">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteCategorie">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="categorieList" :row-class-name="rowCategorieIndex" @selection-change="handleCategorieSelectionChange" ref="categorie">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="分类" prop="categoryName" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.categoryName" placeholder="请选择分类">
                <el-option
                  v-for="dict in productcategories"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <!-- <el-table-column label="一级分类" prop="parentCategoryName" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.parentCategoryName" placeholder="请选择一级分类">
                <el-option
                  v-for="dict in productcategories01"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column> -->
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/product/product";
import { addCart } from "@/api/cart/cart";
import { listReviews } from "@/api/reviews/reviews";
import Cookies from 'js-cookie';  //cookies的使用要求引入
const { proxy } = getCurrentInstance();
const showAddButton = ref(false); // 默认显示
const showBuyButton = ref(true);
const { productcategories01, productcategories, sold_status } = proxy.useDict('productcategories01', 'productcategories', 'sold_status');
const productList = ref([]);
const productListSoler = ref([]);
const reviewsList = ref([]);
const reviewsList01 = ref([]);
const categorieList = ref([]);
const open = ref(false);
const reviews = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedCategorie = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: null,
    price: null,
    stockQuantity: null,
    categoryName: null,
    brand: null,
    isAvailable: null,
  },
  query:{
    userName:"",
    productId:null,
    rating:null,
    comment:"",
    reviewDate:""
  },
  rules: {
    productName: [
      { required: true, message: "商品名不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "价格不能为空", trigger: "blur" }
    ],
    stockQuantity: [
      { required: true, message: "商品库存不能为空", trigger: "blur" }
    ],
    isAvailable: [
      { required: true, message: "可购买？不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules ,query} = toRefs(data);

/** 查询商品列表 */
// 想要展示的变量可以在这里进行初始化
function getList() {
  loading.value = true;
  let userName=Cookies.get("username");
  listProduct(queryParams.value).then(response01 => {
    const rows = response01.rows;
    ///////////////////////////////////////
    rows.forEach(item => {
      item.quantity = 0;
      item.total_amount=0; // 初始化购买数量
      categoryName: queryParams.value.categoryName || undefined // 传递undefined而不是null
      isAvailable: queryParams.value.isAvailable || undefined // 传递undefined而不是null   
    });
    if(Cookies.get("username")=="sqlstudent1"||Cookies.get("username")=="admin"){
      showBuyButton.value=false;
      showAddButton.value=true;
      queryParams.value.userName=userName;
      listProduct(queryParams.value).then(response01 => { 
        console.log(response01.rows);
        productList.value = response01.rows;
       });
    }
    else{
      productList.value = rows;
    }
    /////////////////////////////////


    total.value = response01.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    productId: null,
    productName: null,
    categoryId: null,
    description: null,
    price: null,
    stockQuantity: null,
    categoryName: null,
    brand: null,
    imageUrl: null,
    isAvailable: null
  };
  categorieList.value = [];
  proxy.resetForm("productRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.productId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _productId = row.productId || ids.value
  getProduct(_productId).then(response => {
    form.value = response.data;
    categorieList.value = response.data.categorieList;
    open.value = true;
    title.value = "修改商品";
  });
}

// 获取评论信息
function getReviews(row) {
  query.value.productId=row.productId;
   ///////////////////////
  listReviews(query.value).then(response => {
    reviewsList.value=response.rows;
    reviews.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      form.value.categoryName = categorieList.value[0].categoryName;
      form.value.userName = Cookies.get("username");
      if (form.value.productId != null) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
  
        });
      } else {
        //////////////////////////////////
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
        
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _productIds = row.productId || ids.value;
  proxy.$modal.confirm('是否确认删除商品编号为"' + _productIds + '"的数据项？').then(function() {
   
      return delProduct(_productIds);
        
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 分类序号 */
function rowCategorieIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 分类添加按钮操作 */
function handleAddCategorie() {
  let obj = {};
  obj.categoryName = "";
  obj.parentCategoryName = "";
  categorieList.value.push(obj);
}

/** 分类删除按钮操作 */
function handleDeleteCategorie() {
  if (checkedCategorie.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的分类数据");
  } else {
    const categories = categorieList.value;
    const checkedCategories = checkedCategorie.value;
    categorieList.value = categories.filter(function(item) {
      return checkedCategories.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleCategorieSelectionChange(selection) {
  checkedCategorie.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('product/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

function addToCart(row) {
    // 调用 addCart 方法并传递当前行的数据
    // 检查数量是否大于0
    if (!row.quantity || row.quantity <= 0) {
        proxy.$modal.msgWarning("购买量不能为0");
        return; // 直接返回，不执行后续代码
    }
    
    // 检查库存是否足够
    if (row.quantity > row.stockQuantity) {
        proxy.$modal.msgWarning("购买数量不能超过库存数量");
        return;
    }
    row.userName=Cookies.get('username');
    addCart(row).then(response => {
      // 处理响应结果
      proxy.$modal.msgSuccess("加入购物车成功");
    }).catch(error => {
      // 处理错误
      proxy.$modal.msgSuccess("加入购物车失败");
    });
  }


  function increaseQuantity(row) {
    // 增加购买数量
    if (row.quantity < row.stockQuantity) {
      row.quantity += 1;
      row.total_amount=row.quantity * row.price;
    } else {
      this.$message.warning('库存不足，无法继续增加购买数量');
    }
  }

getList();
</script>
